<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\order\OrderItem;
use think\Controller;
use think\Db;
use think\Model;

class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public  function  orderSure()
    {
        $param = $this->request->param();

        $param['goodsId'] = explode(',', $param['goodsId']);
        $param['goodnum'] = explode(',', $param['goodnum']);
        $param['key'] = explode(',', $param['key']);
        $info = [];
        foreach ($param['goodsId'] as $key => $value) {
            $info[$key]['goodsId'] = $value;
        }
        foreach ($param['goodnum'] as $key => $value) {
            $info[$key]['num'] = $value;
        }
        foreach ($param['key'] as $key => $value) {
            $info[$key]['key'] = $value;
            if ($value) {
                $info[$key]['is_sku'] = 1;
            } else {
                $info[$key]['is_sku'] = 0;
            }
        }


        $param = [
            'uid' => $this->auth->id,
            'data' => $info,
        ];

        $data =(new \app\common\model\Order())->order_sure($param,1);

        $this->success('',$data);
    }
    /**
     * 生成订单
     */
    public function setUpOrder()
    {
        $param = $this->request->param();

        $param['goodsId'] = explode(',', $param['goodsId']);
        $param['goodnum'] = explode(',', $param['goodnum']);
        $param['key'] = explode(',', $param['key']);
        $info = [];
        $order_type_arr=[1,2];
        if(empty($param['order_type'])){
            $param['order_type']=1;
        }
        if(empty($param['pickup_id'])){
            $param['pickup_id']=0;
        }

        foreach ($param['goodsId'] as $key => $value) {
            $info[$key]['goodsId'] = $value;
        }
        foreach ($param['goodnum'] as $key => $value) {
            $info[$key]['num'] = $value;
        }
        foreach ($param['key'] as $key => $value) {
            $info[$key]['key'] = $value;
            if ($value) {
                $info[$key]['is_sku'] = 1;
            } else {
                $info[$key]['is_sku'] = 0;
            }
        }

        $param = [
            'uid' => $this->auth->id,
            'note' => $param['note'],
            'data' => $info,
            'openid'=>$param['openid'],
        ];

        foreach ($param['data'] as $k => $v) {
            $stocks=\app\common\model\Goods::where(['id'=>$v['goodsId'],'status'=>1])->find();
            if(!$stocks){
                $this->error('商品已下架');
            }
            if($stocks['goods_num']<$v['num']){
                $this->error('库存不足');
            }
        }



        #生成订单
        $result2 =(new \app\common\model\Order())->create_order($param);

        if ($result2['code'] == 200) {
            //去支付
            //订单信息
            $order = db('order')->where(['id' => $result2['order_id']])->find();
            if (!$order) {
                return json(['code' => 400, 'msg' => '订单记录查找不到']);
            }
            $wxuser = db('user_third')->where('user_id', $order['user_id'])->find();

            $pay_info = [
                'openid' => $wxuser['openid'],
                'body' => '微信支付',
                'detail' => '微信支付',
                'ordernum' => $order['order_sn'],
                'money' => $order['total_fee'],
                'notify_url' => '',
            ];  $wxpay = new WxPay();

            $wxconfig = $wxpay->union_order($pay_info);

            if ($wxconfig) {
                $update_data=[
                    'wxconfig' => json_encode($wxconfig),
                ];

                db('order')->where('id', $result2['order_id'])->update($update_data);
                $this->success('',['wxconfig' => $wxconfig,'is_pay'=>1]);
            } else {
              $this->error('支付失败');
            }



        }else{
            $this->error($result2['msg']);
        }
    }

    public function payNow()
    {
        $param = $this->request->param();
        $order= (new \app\common\model\Order())->where(['id'=>$param['order_id'],'user_id'=>$this->auth->id,'status'=>0])->find();
        if(!$order){
            $this->error('订单不存在');
        }


        $order = db('order')->where(['id' => $order['id']])->find();
        if (!$order) {
            return json(['code' => 400, 'msg' => '订单记录查找不到']);
        }
        $wxuser = db('user_third')->where('user_id', $order['user_id'])->find();

        $pay_info = [
            'openid' => $wxuser['openid'],
            'body' => '微信支付',
            'detail' => '微信支付',
            'ordernum' => $order['order_sn'],
            'money' => $order['total_fee'],
            'notify_url' => '',
        ];
        $wxpay = new WxPay();

        $wxconfig = $wxpay->union_order($pay_info);

        if ($wxconfig) {
            $update_data=[
                'wxconfig' => json_encode($wxconfig),
            ];

            db('order')->where('id', $order['id'])->update($update_data);
            $this->success('',['wxconfig' => $wxconfig,'is_pay'=>1]);
        } else {
            $this->error('支付失败');
        }
    }

    public function cancelOrder()
    {
        $param = $this->request->param();
        $order= (new \app\common\model\Order())
            ->where(['id'=>$param['order_id'],'user_id'=>$this->auth->id,'status'=>0])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        Db::startTrans();
        $res =(new \app\common\model\Order())
            ->where(['id'=>$param['order_id'],'user_id'=>$this->auth->id,'status'=>0])
            ->update(['status'=>-1,'cancel_time'=>time(),'order_status'=>-1]);
        if($res){
            $orderitem =(new OrderItem())->where(['order_id'=>$param['order_id']])->select();
            foreach ($orderitem as $k => $v){
                db('goods')->where('id', $v['goods_id'])->setDec('goods_sales', $v['goods_num']);
              db('goods')->where('id', $v['goods_id'])->setInc('goods_num', $v['goods_num']);
            }
            Db::commit();
            $this->success('取消成功');
        }else{
            Db::rollback();
            $this->error('取消失败');
        }
    }

    public function myorders()
    {
        $params=$this->request->param();
        $where['user_id']=$this->auth->id;
        if(!empty($params['status'])){
            if($params['status']==1){
                $where['status']=0;
            }
            if($params['status']==2){
                $where['status']=1;
            }
            if($params['status']==3){
                $where['status']=2;
            }
            if($params['status']==4){
                $where['status']=-2;
            }
            if($params['status']==5){
                $where['status']=-1;
            }
        }

        $data=\app\common\model\order\Order::with(['orderitem'])

            ->where($where)
            ->order(['createtime'=>'desc'])
            ->paginate();
        foreach ($data as $k=>$v){
            $v->append=['canceltime_time'=>'','order_date_text'=>''];
            $v['order_date_text']=date('Y-m-d',$v['order_date']);
            $v['canceltime_time']=  date('Y/m/d H:i:s',$v['pre_time']);
        }
        $this->success('',$data);

    }


    public function getOrderNums()
    {
        $data['nopay']    =\app\common\model\Order::where(['status'=>0,'user_id'=>$this->auth->id])->count();
        $data['appoints'] =\app\common\model\Order::where(['status'=>1,'user_id'=>$this->auth->id,'is_appoint'=>['<',2]])->count();
        $data['finish'] =\app\common\model\Order::where(['status'=>1,'user_id'=>$this->auth->id,'is_appoint'=>2])->count();
        $data['refunds']  =\app\common\model\Order::where(['status'=>-2,'user_id'=>$this->auth->id])->count();;
        $data['cancel']   =\app\common\model\Order::where(['status'=>-1,'user_id'=>$this->auth->id])->count();;
        $this->success('',$data);
    }

    public function orderDetail()
    {
        $param = $this->request->param();
        $data=\app\common\model\order\Order::with(['orderitem'])
            ->where(['user_id'=>$this->auth->id,'id'=>$param['order_id']])
            ->find();
        if($data){
            $data['order_date_text']=date('Y-m-d',$data['order_date']);
            $data['canceltime_time']=  date('Y/m/d H:i:s',$data['pre_time']);
        }
        $this->success('',$data);
    }

}